package com.sugar.real.estate.module.business.util;

import com.sugar.real.estate.module.business.enums.config.ConfigEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ResourceBundleMessageSource;

import java.nio.charset.StandardCharsets;
import java.util.Locale;
import java.util.Objects;

/**
 * @author Y.sugar
 * @since 2025/7/29 15:09
 */
@Slf4j
public class I18nUtil {

    public static final ResourceBundleMessageSource MESSAGE_SOURCE;

    static {
        MESSAGE_SOURCE = new ResourceBundleMessageSource();
        MESSAGE_SOURCE.setDefaultEncoding(StandardCharsets.UTF_8.toString());
        MESSAGE_SOURCE.setBasename("i18n/messages");
    }

    /**
     * 获取 国际化后内容信息
     *
     * @param code 国际化key
     * @return 国际化后内容信息
     */
    public static String getMessage(String code) {
        return MESSAGE_SOURCE.getMessage(code, null, LocaleContextHolder.getLocale());
    }

    public static boolean isChinese() {
        Locale locale = LocaleContextHolder.getLocale();
        String language = locale.getLanguage().toLowerCase();
        String country = locale.getCountry().toLowerCase();
        return language.equals("zh") && country.equals("cn");
    }

    /**
     * 获取 国际化后内容信息
     *
     * @param obj           待取值对象
     * @param getMethodName 字段名Get方法名称
     * @return 国际化后内容信息
     */
    public static String getMessage(Object obj, String getMethodName) {
        Locale locale = LocaleContextHolder.getLocale();
        String language = locale.getLanguage().toLowerCase();
        String country = locale.getCountry().toLowerCase();
        if ((language.equals("zh") && country.equals("cn")) || (language.equals("en") && country.equals("us")))
            getMethodName = getMethodName + capitalizeFirstLetter(language) + capitalizeFirstLetter(country);
        else
            getMethodName = getMethodName + "ZhCn";
        Object result = MethodUtil.invoke(obj, getMethodName);

        return Objects.nonNull(result) ? (String) result : null;
    }

    /**
     * 获取 国际化后内容信息
     *
     * @param name 待取值对象
     * @return 国际化后内容信息
     */
    public static ConfigEnum getConfigEnumVal(String name) {
        Locale locale = LocaleContextHolder.getLocale();
        String language = locale.getLanguage().toLowerCase();
        String country = locale.getCountry().toLowerCase();

        if (!((language.equals("zh") && country.equals("cn")) || (language.equals("en") && country.equals("us")))) {
            language = "en";
            country = "us";
        }


        return ConfigEnum.find(name + "_" + language + "_" + country);
    }

    private static String capitalizeFirstLetter(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }
}
